import { extract } from './number.js';

/* 
	按区间取值
 */
function collapse(value, range) {
	const [min, max] = range;
	if (value < min) {
		return min;
	} else if (value > max) {
		return max;
	} else {
		return value;
	}
}

/* 
	四舍五入数字至指定小数位
 */
function roundFixed(number, decimals) {
	if (decimals > 0) {
		return Math.round(Math.pow(10, decimals) * number) / Math.pow(10, decimals);
	} else if (decimals < 0) {
		return Math.round(number / Math.pow(10, Math.abs(decimals))) * Math.pow(10, Math.abs(decimals));
	} else {
		return number;
	}
}

/* 
	数字按金额格式化
 */
function moneyFormat(money, decimals = 2, digit = 3) {
	const pattern = new RegExp(`(-?\\d+)(\\d{${digit}})`);
	let [prefix, suffix] = roundFixed(extract(money), decimals).toString().split('.');
  while (pattern.test(prefix)) prefix = prefix.replace(pattern, "$1,$2");
  return `${prefix}.${suffix}`;
}

/* 
	贝塞尔曲线
 */
function threeBezier(t, p1, cp1, cp2, p2) {
	const [x1, y1] = p1;
	const [x2, y2] = p2;
	const [cx1, cy1] = cp1;
	const [cx2, cy2] = cp2;
	let x =
		x1 * (1 - t) * (1 - t) * (1 - t) +
		3 * cx1 * t * (1 - t) * (1 - t) +
		3 * cx2 * t * t * (1 - t) +
		x2 * t * t * t;
	let y =
		y1 * (1 - t) * (1 - t) * (1 - t) +
		3 * cy1 * t * (1 - t) * (1 - t) +
		3 * cy2 * t * t * (1 - t) +
		y2 * t * t * t;
	return [x, y];
}

/* 
	指定段数按贝塞尔曲线分割
 */
function gradientNumber(num, parts, timing = 'linear') {
	const part = 1 / parts, nums = [0];
	let pre = 0, points;
	switch(timing) {
		case 'linear': points = [[0, 0], [0, 0], [1, 1], [1, 1]]; break;
		case 'ease-in': points = [[0, 0], [0.42, 0], [1, 1], [1, 1]]; break;
		case 'ease-out': points = [[0, 0], [0, 0], [0.58, 1], [1, 1]]; break;
		case 'ease-in-out': points = [[0, 0], [0.42, 0], [0.58, 1], [1, 1]]; break;
		default: break;
	}
	for (let i = 1; i <= parts; i++) {
		let point = threeBezier(part * i, points[0], points[1], points[2], points[3]);
		nums.push((point[1] - pre) * num);
		pre = point[1];
	}
	return nums;
}

/* 
	获取指定范围随机数
 */
function randomNumber(min, max) {
	return Math.random() * (max - min) + min;
}

export {
	collapse,
	roundFixed,
	moneyFormat,
	threeBezier,
	gradientNumber,
	randomNumber
}